package com.atguigu.filter;

import com.atguigu.dao.BaseDao;
import com.atguigu.utils.JDBCUtils;
import com.sun.deploy.net.HttpRequest;
import com.sun.deploy.net.HttpResponse;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * 全局事务 管理所有方法
 * @author dl
 * @date 2020/5/7 12:20
 */
public class GlobalFilter implements Filter {
    /**
     * 销毁方法
     */
    @Override
    public void destroy() {

    }
    /**
     * 执行方法
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 在这里对事物进行控制
        Connection connection = JDBCUtils.getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
            connection.commit();
        } catch (Exception e) {
            // why not go there
            // 打印异常信息
            System.out.println("GlobalFilter " + e.getMessage());
            // 回滚
            try {
                connection.rollback();
            } catch (Exception throwables) {
                throwables.printStackTrace();
            }
            //关闭连接
            JDBCUtils.releaseConnection();
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            // go to exception page
            response.sendRedirect(request.getContextPath() + "/exception.jsp");
        }
        JDBCUtils.releaseConnection();
    }
    /**
     * 初始化方法
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


}
